package com.cloudfun.campusshare.configuration.jpa;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.jpa.repository.support.*;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.util.Assert;

import javax.persistence.EntityManager;
import java.io.Serializable;
import java.lang.reflect.Type;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/5/19 17:51
 **/
@Slf4j
public class GaodaoRepositoryFactoryBean<T extends Repository<S, ID>, S, ID> extends JpaRepositoryFactoryBean<T, S, ID> {
    public GaodaoRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new GaodaoRepositoryFactory(entityManager);
    }

    private class GaodaoRepositoryFactory<T, ID extends Serializable> extends JpaRepositoryFactory {
        private final EntityManager em;

        public GaodaoRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.em = entityManager;
        }

        @Override
        protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information, EntityManager entityManager) {
            JpaEntityInformation<?, Serializable> entityInformation = super.getEntityInformation(information.getDomainType());
            Object repository = super.getTargetRepositoryViaReflection(information, new Object[]{entityInformation, entityManager});
            if(repository instanceof GaodaoRepository){
                return (GaodaoRepositoryImpl)repository;
            }else{
                Assert.isInstanceOf(JpaRepositoryImplementation.class, repository);
                return (JpaRepositoryImplementation)repository;
            }
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            Class<?> superClass = metadata.getRepositoryInterface().getInterfaces()[0];
            if(GaodaoRepository.class.isAssignableFrom(superClass)){
                return GaodaoRepositoryImpl.class;
            }else{
                return SimpleJpaRepository.class;
            }
        }
    }
}
